`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:  X-Speed.com.cn
// Engineer: yansf
// 
// Create Date:    01/16/2024
// Design Name: 
// Module Name:    FeedWDT 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////

module FeedWDT(
	Clk, 
	nRst, 
	Clk_5ms,
	Clk_1s,
	WDI, 
	WDT_EN,
	CPU_Feed,
	WDT_MR,
	TimeOutSecs,
	// ------- Debug
	Time_Cnt
);

input 	Clk, nRst, Clk_5ms, Clk_1s; 
input 	WDT_EN, CPU_Feed;
input 	[7:0] TimeOutSecs;

output 	[7:0] Time_Cnt;
output 	WDI;
output 	WDT_MR;	

wire		WDT_MR = 1'b1;

reg [7:0] 	Time_Cnt = 8'h00;
reg 		last_Clk_1s = 1'b0;
reg 		last_CPU_Feed = 1'b0;
reg 		b_WDT_OverTime = 1'b0;

assign WDI = b_WDT_OverTime ? 1'b1 : Clk_5ms;  //if wdt wait over time, down feed SGM823

always @( posedge Clk or negedge nRst )
begin
	if (!nRst)
		begin
			last_Clk_1s <= 1'b0;
			last_CPU_Feed <= 1'b0;
		end
	else
		begin
			last_Clk_1s <= Clk_1s;
			last_CPU_Feed <= CPU_Feed;
		end	
end


always @( posedge Clk )
begin
	if ( !nRst || !WDT_EN || (last_CPU_Feed != CPU_Feed))	// Reset or Disable or feed WDT
		begin
			Time_Cnt <= 8'h00;
			b_WDT_OverTime <= 1'b0;
		end 
	else 
		begin
			if (Time_Cnt >= TimeOutSecs)	// Time out, keep this State untill the Real WDT Reset FPGA
				begin
					Time_Cnt <= TimeOutSecs;
					b_WDT_OverTime <= 1'b1;
				end
			else 
				begin
					if ( last_Clk_1s==1'b0 & Clk_1s==1'b1 )	// every posedge of Clk_1s Cnting
						begin
							Time_Cnt <= Time_Cnt+1'b1;
							b_WDT_OverTime <= 1'b0;
						end
					else
						begin
							b_WDT_OverTime <= b_WDT_OverTime;
							Time_Cnt <= Time_Cnt;
						end
				end
		end
end

endmodule